package com.exampl.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.exampl.dao.SetmealDao;
import com.exampl.domain.Dish;
import com.exampl.domain.Setmeal;
import com.exampl.domain.SetmealDish;
import com.exampl.dto.SetmealDto;
import com.exampl.service.DishService;
import com.exampl.service.SetmealDishService;
import com.exampl.service.SetmealService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealDao, Setmeal> implements SetmealService {

    @Autowired
    SetmealDishService setmealDishService;

    @Override
    @Transactional  // 开启事务
    public void saveWithDish(SetmealDto setmealDto) {
        // 保存套餐
        this.save(setmealDto);
        // 获取套餐id
        Long id = setmealDto.getId();
        // 获取套餐内容
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list = list.stream().peek((data) -> data.setSetmealId(id)).collect(Collectors.toList());
        setmealDishService.saveBatch(list);
    }

    @Override
    public SetmealDto getWithDish(Long id) {
        SetmealDto dto = new SetmealDto();
        Setmeal setmeal = this.getById(id);
        BeanUtils.copyProperties(setmeal, dto);
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<SetmealDish>();
        lqw.eq(SetmealDish::getSetmealId, id);
        List<SetmealDish> dishes = setmealDishService.list(lqw);
        dto.setSetmealDishes(dishes);
        return dto;
    }

    @Override
    @Transactional  // 开启事务
    public void updateWithDish(SetmealDto setmealDto) {
        // 更新套餐
        this.updateById(setmealDto);
        // 删除套餐中的菜品
        Long id = setmealDto.getId();
        LambdaQueryWrapper<SetmealDish> lqw = new LambdaQueryWrapper<SetmealDish>();
        lqw.eq(SetmealDish::getSetmealId, id);
        setmealDishService.remove(lqw);
        // 重新添加套餐中的菜品
        List<SetmealDish> dishes = setmealDto.getSetmealDishes();
        dishes = dishes.stream().peek((data) -> data.setSetmealId(id)).collect(Collectors.toList());
        setmealDishService.saveBatch(dishes);
    }
}
